#!/usr/bin/env python
# Create: 2018/12/6
__author__ = '749B'

import logging
import os

from backend.ssh_client import SSHClient

logger = logging.getLogger(__name__)


class AddClient(SSHClient):

    def __init__(self, conf_obj, *args, **kwargs):
        super(AddClient, self).__init__(*args, **kwargs)
        self.conf_obj = conf_obj

    def main(self):
        self.get_ssh_and_save_conf()
        self.deploy()
        self.ssh.close()

    def get_ssh_and_save_conf(self):
        self.get_ssh()
        self.conf_obj.save()

    def deploy(self):
        service = ['rsyslog']
        for s in service:
            if self.has_service(s):
                func = getattr(self, 'deploy_%s' % s)
                break
        else:
            logger.error("没有发现以下服务: %s" % ', '.join(service))
            return
        func()

    def has_service(self, service):
        cmd_line = "service %s status" % service
        res, err = self.exec_command(cmd_line, res_report=False, err_report=False)
        if res:
            return True

    def deploy_rsyslog(self):
        backend_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        report = []
        service_status = []
        log_msg_prefix = '在 %s 上' % self.host

        def create_remote_file(remotepath, localpath, restart_service=None):
            """去服务器上创建配置文件，之后重启服务"""
            is_exists = self.path_exists(remotepath, res_report=False, err_report=False)
            if is_exists:
                report.append("配置文件已存在: %s" % remotepath)
                return

            with open(localpath) as f:
                content = f.read()
            cmd_line = "echo \"%s\" >> %s" % (content.replace(r'"', r'\"'), remotepath)
            _, err = self.exec_command(cmd_line)
            msg = "创建配置文件: %s" % remotepath
            report.append(msg)
            logger.info("%s%s" % (log_msg_prefix, msg))
            if err:
                msg = "创建配置文件 %s 时返回 ERROR: %s" % (remotepath, err)
                report.append(msg)
                logger.error("%s%s" % (log_msg_prefix, msg))

            # 重启服务
            if restart_service is None:
                return
            cmd_line = "service %s restart" % restart_service
            self.exec_command(cmd_line, res_report=False, err_report=False)
            cmd_line = "service %s status" % restart_service
            res, err = self.exec_command(cmd_line, res_report=False, err_report=False)
            service_status.append("%s 服务状态:\n%s" % (restart_service, res.decode()))
            msg = "查询了 %s 的服务状态" % restart_service
            logger.info("%s%s" % (log_msg_prefix, msg))
            if err:
                service_status.append("%s 服务状态返回错误:\n%s" % (restart_service, err.decode()))
                msg = "查询 %s 服务状态时，返回错误: %s" % (restart_service, err.decode())
                logger.info(("%s%s" % (log_msg_prefix, msg)).rstrip())

        # 创建配置文件
        remotepath = r'/etc/rsyslog.d/logaudit.conf'
        localpath = os.path.join(backend_folder, 'config', 'rsyslog.d', 'logaudit.conf')
        create_remote_file(remotepath, localpath, 'rsyslog')

        remotepath = r'/etc/logrotate.d/logaudit'
        localpath = os.path.join(backend_folder, 'config', 'logrotate.d', 'logaudit_root')
        create_remote_file(remotepath, localpath)  # 日志轮训不用重启

        # 打印报告
        report.extend(service_status)
        print('Report'.center(50, '*'))
        print('\n'.join(report))
        print('End Report'.center(50, '*'))





